import React, { useEffect, useState } from "react";
function UseEffectFunction() {
    console.log('函数被执行')
    const initialTimer=10;
    //2:timer初始值
    const [timer, setTimer] = useState(initialTimer);
    //setTimer接受的是一个事件对象
    const onX = () => {
        setTimer(timer * 2);
    }
    const onMinus = () => {
        setTimer(timer - 1);
    }
    const onReset = () => {
        setTimer(initialTimer);
    }
    // 定时器
    useEffect(()=>{
        setInterval(()=>{
            console.log('timer',timer);
            /*
            setTimer(timer+1):一直调用的是initialTimer，setTimer()函数会重新执行
            setTimer(oldTimer=>oldTimer+1);使用回调函数【react闭包】，修改之前的值
            */
            setTimer(oldTimer=>oldTimer+1);
        },1000);
    },[]);

    return (<>
        <button onClick={onX}>乘2</button>
        <button onClick={onMinus}>减一</button>
        <button onClick={onReset}>重置</button>
        <div>time: {timer}</div>
    </>);
}
export default UseEffectFunction;